/**
 * 费用基础设置详情
 */
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { messages } from "share/common";
import { Checkbox, Form, Radio } from 'antd'
import SlideFrameContent from '../slide-frame-content'
import settingService from '../request-and-expense-settings.service'

const RadioGroup = Radio.Group;

class CostBaseSettingDetail extends Component {

  record = this.props.params.record;

  state = {
    enableReceiptDiffCheck: this.record.invoiceOptId ? this.record.enableReceiptDiffCheck : true,
    enableAutoPushExpense: this.record.invoiceOptId ? this.record.autoPushExpense : false
  };

  priorityInfo = {
    top: (this.props.authPolicyAll || this.record.invoiceOptId) ? 'TENANT' : 'COMPANY',
    disabled: !!this.record.invoiceOptId,
    value: this.record.invoiceOptId ? {
      levelCode: this.record.levelCode,
      levelOrgId: this.record.levelOrgId,
      levelOrgName: this.record.levelOrgName,
      distribution: {
        companies: this.record.companyInfos
      }
    } : {
      levelCode: this.props.authPolicyAll ? 'TENANT' : 'COMPANY',
      levelOrgId: this.props.authPolicyAll ? this.props.tenant.id : this.props.company.id,
      levelOrgName: this.props.authPolicyAll ? this.props.tenant.tenantName : this.props.company.name,
    }
  };

  radioOptions = [
    {label: messages('common.yes')/*是*/, value: true},
    {label: messages('common.no')/*否*/, value: false},
  ];

  radioOptions2 = [
    {label: messages('expense-5.key19')/*小于等于*/, value: 3},
    {label: messages('expense-5.key30')/*等于*/, value: 2},
    {label: messages('expense-5.key31')/*不校验*/, value: 1},
  ];

  radioOptions3 = [
    {label: messages('expense-5.key19')/*小于等于*/, value: 0},
    {label: messages('expense-5.key30')/*等于*/, value: 2},
    {label: messages('expense-5.key31')/*不校验*/, value: 1},
  ];

  radioOptions4 = [
    {label: messages('common.yes')/*是*/, value: 1},
    {label: messages('common.no')/*否*/, value: 0},
  ];

  amountCheckOptions = [
    {label: messages('expense-5.key19')/*小于等于*/, value: 1},
    {label: messages('expense-5.key30')/*等于*/, value: 2},
    {label: messages('expense-5.key31')/*不校验*/, value: 3}
  ];

  checkRangeOptions = [
    { label: messages('expense-5.key32')/*费用的发生日期 与 发票的开票日期 校验*/, value: 'receiptBillDateCheck' },
    { label: messages('expense-5.key33')/*费用的城市、出发地、目的地 与 发票的地点 校验*/, value: 'receiptCityCheck' },
    { label: messages('expense-5.key34')/*费用的舱等座次 与 发票的舱等座次 校验*/, value: 'receiptCabinCheck' },
    { label: messages('expense-5.key35')/*费用的出发时间、到达时间 与 发票的时间 校验*/, value: 'receiptTravelDateCheck' },
  ];
  autoPushExpenseListOptions = [
    {label: messages('expense-5.key36')/*高德打车*/, value: 'autoPushGaode'},
    {label: messages('expense-5.key37')/*滴滴出行*/, value: 'autoPushDiDi'},
  ];

  extraMessage = messages('expense-5.key4')/*配置费用详情是否显示替票控件。为“是”则费用详情页显示替票控件；为“否”则不显示。报销单默认打印员工填写的替票理由，可至<a onclick=\"window.open('/main/setting/expense-setting', '_blank')\">【报销设置】</a>页面更改设置*/;

  // 校验费用与发票一致性范围默认值
  defaultCheckRange = ['receiptBillDateCheck', 'receiptCabinCheck', 'receiptCityCheck', 'receiptTravelDateCheck'];

  getCheckRangeValue = record => {
    let values = [];
    record.receiptBillDateCheck && values.push('receiptBillDateCheck');
    record.receiptCabinCheck && values.push('receiptCabinCheck');
    record.receiptCityCheck && values.push('receiptCityCheck');
    record.receiptTravelDateCheck && values.push('receiptTravelDateCheck');
    return values;
  };
  getAutoExpenseListValues() {
    if (this.record.invoiceOptId && this.record.autoPushExpense) {
      return this.autoPushExpenseListOptions.map(item => {
        if (this.record[item.value]) {
          return item.value
        } else {
          return ''
        }
      }).filter(value => value);
    }
    return ['autoPushGaode'];
  };
  formList1 = [{
    id: 'enableInstead',
    label: messages('expense-5.key6')/*是否允许【替票】*/,
    extra: <span dangerouslySetInnerHTML={{__html: this.extraMessage}} />,
    initialValue: this.record.invoiceOptId ? this.record.enableInstead: false,
    component: <RadioGroup disabled={this.record.readOnly} options={this.radioOptions}/>
  }, {
    id: 'enableDeliver',
    label: messages('expense-5.key7')/*是否允许费用【转交】*/,
    extra: messages('expense-5.key8')/*配置费用是否允许转交给他人。为“是”则允许且账本内显示转交按钮；为“否”则不允许且账本内不显示转交按钮*/,
    initialValue: this.record.invoiceOptId ? this.record.enableDeliver: false,
    component: <RadioGroup disabled={this.record.readOnly} options={this.radioOptions}/>
  }, {
    id: 'batchImport',
    label: messages('expense-5.key9')/*是否允许批量导入费用*/,
    extra: messages('expense-5.key10')/*配置是否允许批量导入费用。为“是”则在报销单详情页显示【批量导入费用】功能按钮；为“否”则不显示功能按钮*/,
    initialValue: this.record.invoiceOptId ? this.record.batchImport: false,
    component: <RadioGroup disabled={this.record.readOnly} options={this.radioOptions}/>
  }, {
    id: 'relevantInParticipants',
    label: messages('expense-5.key11')/*是否配置费用分摊相关人范围*/,
    extra: messages('expense-5.key12')/*配置为“否”则费用分摊相关人为账套下所有人，配置为“是”则费用分摊相关人范围为报销单参与人加费用归属人*/,
    initialValue: this.record.invoiceOptId ? this.record.relevantInParticipants || 0 : 0,
    component: <RadioGroup disabled={this.record.readOnly} options={this.radioOptions4}/>
  }, {
    id: 'enableReceiptDiffCheck',
    label: messages('expense-5.key13')/*是否校验费用与发票一致性*/,
    extra: messages('expense-5.key14')/*配置费用关联单张发票时，是否校验费用与关联的的发票信息是否一致。为“否”，则不校验；为“是”，则根据勾选范围，仅字段有值时校验，存在任意字段不一致则在费用上标记“与发票不一致”*/,
    initialValue: this.record.invoiceOptId ? this.record.enableReceiptDiffCheck : true,
    component: (
      <RadioGroup
        disabled={this.record.readOnly}
        options={this.radioOptions}
        onChange={e => this.setState({ enableReceiptDiffCheck: e.target.value })}
      />
    )
  }, {
    id: 'enableReceiptDiffCheckRange',
    label: " ",
    extraProps: { className: 'diff-check-range' },
    initialValue: this.record.invoiceOptId ? this.getCheckRangeValue(this.record) : this.defaultCheckRange,
    component: <Checkbox.Group options={this.checkRangeOptions}/>
  }, {
    id: 'autoPushExpense',
    label: messages('expense-5.key38')/*是否允许自动推送费用*/,
    extra: this.renderAutoPushExpenseExtra(),
    initialValue: this.record.invoiceOptId ? this.record.autoPushExpense || false : false,
    component: <RadioGroup disabled={this.record.readOnly}
                           options={this.radioOptions}
                           onChange={e => this.setState({ enableAutoPushExpense: e.target.value })}/>
  }, {
    id: 'autoPushExpenseList',
    label: messages('expense-5.key39')/*请勾选允许员工使用的消费商*/,
    extraProps: { className: 'auto-expense-list' },
    initialValue: this.getAutoExpenseListValues(),
    rules: [{required:true,message:messages('expense-5.key40')/*消费商不能为空*/}],
    component: (<Checkbox.Group>
      {this.autoPushExpenseListOptions.map(item => {
        return (<div>
          <Checkbox value={item.value}>{item.label}</Checkbox>
          <p>{this.renderAutoExpenseItemDetail(item.value)}</p>
        </div>)
      })}
    </Checkbox.Group>)
  }];

  formList2 = [{
    id: 'enableZero',
    label: messages('expense-5.key16')/*费用总金额是否可为0*/,
    extra: messages('expense-5.key17')/*配置费用金额是否可为0*/,
    initialValue: this.record.invoiceOptId ? this.record.enableZero: false,
    component: <RadioGroup disabled={this.record.readOnly} options={this.radioOptions}/>
  }, {
    id: 'bizCardCheck',
    label: messages('expense-5.key18')/*费用金额与商务卡金额校验*/,
    extra: messages('expense-5.key20')/*按照配置比较费用金额与费用上关联的商务卡消费记录总金额*/,
    initialValue: this.record.invoiceOptId ? this.record.bizCardCheck: 3,
    component: <RadioGroup disabled={this.record.readOnly} options={this.radioOptions2}/>
  }, {
    id: 'amountReceiptCheck',
    label: messages('expense-5.key21')/*费用金额与发票价税合计总和校验*/,
    extra: messages('expense-5.key22')/*按照配置比较费用金额与费用上关联的发票价税合计总和（如果允许重复发票生成费用，则对于重复发票会跨费用校验）*/,
    initialValue: this.record.invoiceOptId ? this.record.amountReceiptCheck: 0,
    component: <RadioGroup disabled={this.record.readOnly} options={this.radioOptions3}/>
  }, {
    id: 'pcfpAmountCheck',
    label: messages('expense-5.key23')/*里程补贴费用金额是否等于补贴金额*/,
    extra: messages('expense-5.key24')/*按照配置比较里程补贴费用金额与补贴金额*/,
    initialValue: this.record.invoiceOptId ? this.record.pcfpAmountCheck: 1,
    component: <RadioGroup disabled={this.record.readOnly} options={this.amountCheckOptions}/>
  }];
  getShowExpenseExtra(str,  linkBtn, specialStr) {
    let showExtra = str.split(specialStr);
    return ( <div>
      {showExtra[0]}{linkBtn}{showExtra[1]}
    </div>)
  };
  renderAutoPushExpenseExtra(){
    let linkStr = messages('expense-5.key41')/*【App应用管理】*/;
    let linkBtn = (<a onClick={()=>this.handleLink('application')}>{linkStr}</a>);
    let showExtra = messages('expense-5.key42',{arg1: linkStr})/*配置是否使用自动推送费用功能。为“是”且配置子应用显示（配置路径：{arg1}-“我的子应用”页面），则在app“我的”会显示自动推送费用授权入口，员工授权后即可使用自动推送费用功能；为“否”，则不显示入口。*/;/*配置是否使用自动推送费用功能。为“是”且配置子应用显示（配置路径：{arg1}-“我的子应用”页面），则在app“我的”会显示自动推送费用授权入口，员工授权后即可使用自动推送费用功能；为“否”，则不显示入口。*/
    return (<section>
      {this.getShowExpenseExtra(showExtra, linkBtn, linkStr)}
    </section>);
  };
  renderAutoExpenseItemDetail(value) {
    let expenseLinkStr = messages('expense-5.key43')/*【费用类型】*/;
    let expenseBtn = (<a onClick={()=>this.handleLink('expenseType')}>{expenseLinkStr}</a>);
    let invoiceLinkStr = messages('expense-5.key44')/*【发票管控-发票生成费用】*/;
    let invoiceLinkBtn = (<a onClick={()=>this.handleLink('invoiceCost')}>
      {invoiceLinkStr}
    </a>);
    let linkStr = messages('expense-5.key41')/*【App应用管理】*/;
    let linkStrBtn = (<a onClick={()=>this.handleLink('application')}>{linkStr}</a>);
    if (value === 'autoPushDiDi') {
      return (
        <section className='ant-form-extra'>
          <div>{messages('expense-5.key45')/*注：勾选“滴滴打车”时，请确保完成下述配置，否则无法正常使用此功能。  */}</div>
          {this.getShowExpenseExtra(
            messages('expense-5.key46',{arg1: expenseLinkStr})/*1.确保{arg1}页面“滴滴出行”费用类型状态为启用；*/,
            expenseBtn,
            expenseLinkStr)
          }
          {this.getShowExpenseExtra(
            messages('expense-5.key47',{arg1: invoiceLinkStr})/*2.保存设置后，系统会在{arg1}自动为您配置一条优先级数值为1的规则“允许重复发票生成滴滴打车费用 */,
            invoiceLinkBtn,
            invoiceLinkStr)
          }
        </section>
      )
    } else {
      return (
        <section className='ant-form-extra'>
          <div>{messages('expense-5.key48')/*注：勾选“高德打车”时，请确保完成下述配置，否则无法正常使用此功能。 */}</div>
          {this.getShowExpenseExtra(
            messages('expense-5.key49',{arg1: expenseLinkStr})/*1.确保{arg1}页面“高德打车”费用类型状态为启用；*/,
            expenseBtn,
            expenseLinkStr)
          }
          {this.getShowExpenseExtra(
            messages('expense-5.key50',{arg1: linkStr})/*2.请至{arg1}-“我的子应用”页面，配置“高德打车”子应用显示*/,
            linkStrBtn,
            linkStr)
          }
        </section>
      )
    }
  };
   handleLink = (type) => {
    let urlObj = {
      expenseType: '/main/setting/expense-type',
      application: '/main/setting/sub-application',
      invoiceCost: '/main/setting/invoice-management-control/invoice-to-cost'
    };
    window.open(urlObj[type]);
  };

  checkBeforeSave = values => {
    return new Promise((resolve, reject) => {
      if (
        values.enableReceiptDiffCheck &&
        (!values.enableReceiptDiffCheckRange || values.enableReceiptDiffCheckRange.length === 0)
      ) {
        reject(messages('expense-5.key51')/*请选择费用与发票一致性的校验范围*/);
      } else {
        resolve();
      }
    })
  };

  dealParams = values => {
    this.record.invoiceOptId && (values.invoiceOptId = this.record.invoiceOptId);
    ['receiptBillDateCheck', 'receiptCabinCheck', 'receiptCityCheck', 'receiptTravelDateCheck'].forEach(key => {
      values[key] = values.enableReceiptDiffCheck ? values.enableReceiptDiffCheckRange.includes(key) : false;
    });
    delete values.enableReceiptDiffCheckRange;
    // 自动推送费用方式需要处理
    let autoPushExpenseList = values.autoPushExpenseList || [];
    this.autoPushExpenseListOptions.forEach(item => {
      values[item.value] = autoPushExpenseList.includes(item.value);
    });
    delete values.autoPushExpenseList;
    return values
  };

  render() {
    const { enableReceiptDiffCheck, enableAutoPushExpense } = this.state;
    return (
      <SlideFrameContent
        disabled={this.record.readOnly}
        enabled={this.record.invoiceOptId ? this.record.enabled : true}
        priorityInfo={this.priorityInfo}
        formInfo={[{
          title: messages('expense-5.key5')/*功能设置*/,
          list: this.formList1.map(item => {
            item.id === 'enableReceiptDiffCheckRange' && (item.hide = !enableReceiptDiffCheck);
            item.id === 'autoPushExpenseList' && (item.hide = !enableAutoPushExpense);
            return item;
          })
        }, {
          title: messages('expense-5.key15')/*金额校验*/,
          list: this.formList2
        }]}
        service={settingService.updateCostBaseSetting}
        checkBeforeSave={this.checkBeforeSave}
        dealParams={this.dealParams}
        close={this.props.close}
      />
    )
  }

}

function mapStateToProps(state) {
  return {
    authPolicyAll: state.main.authPolicyAll,
    company: state.login.company,
    tenant: state.login.tenant,
  }
}

const WrappedCostBaseSettingDetail = Form.create()(CostBaseSettingDetail);

export default connect(mapStateToProps)(WrappedCostBaseSettingDetail);
